<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton } from 'element-plus'

import { Table } from '@/components/Table'

import { zcPastureListApi, zcPastureEditApi } from '@/api/fa/pasture'
import { zcPastureEditParkApi } from '@/api/sp/park'
import { useTable } from '@/hooks/web/useTableTest'
import {
  // h,
  ref,
  unref,
  reactive
} from 'vue'
import Edit from './components/Edit.vue'
import See from './components/See.vue'
// import Enclosure from './components/Enclosure.vue'
import Assets from './components/Assets.vue'
import Park from './components/Park.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'
import { useRouter } from 'vue-router'

import city from '@/views/SmartPasture/EverydayPrice/components/city'

// 获取字典
// import { useCache } from '@/hooks/web/useCache'
// const { wsCache } = useCache()
// const dict: any = wsCache.get('dict')
// 字典通过value获取label
// const getDictLabel = (type, value) => {
//   let data = dict[type].find((item) => {
//     return item.value == value
//   })
//   return data ? data.label : ''
// }
const searchRef = ref() // 搜索的标签

const cityData: any = ref() //城市枚举

const provinceChange = (value) => {
  cityData.value = city[value]
  // console.log(value, city[value], 'value')
  const new_search = unref(searchRef)
  new_search.setData({ ...new_search.getData(), city: '' })
}

const Province = (value) => {
  let data = city.area.find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const City = (a, value) => {
  if (a.province) {
    let num = Number(a.province)
    let data = city[num].find((item) => {
      return item.value == value
    })
    // console.log(a, value, 'data')
    return data ? data.label : ''
  }
}

const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconAssets = useIcon({ icon: 'fluent-emoji-high-contrast:cow-face' })
const iconPark = useIcon({ icon: 'carbon:area' })
const iconEnclosure = useIcon({ icon: 'majesticons:map-marker-area' })
const { push } = useRouter()

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: zcPastureListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: false
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'org_name',
    label: '牧场名称',
    fixed: 'left',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'save_total',
    label: '打标数',
    width: 150,
    detail: {
      span: 2
    }
  },
  {
    field: 'save_mortgage',
    label: '抵押数',
    width: 150,
    detail: {
      span: 2
    }
  },
  {
    field: 'save_insure',
    label: '投保数',
    width: 150,
    detail: {
      span: 2
    }
  },
  {
    field: 'legal_name',
    label: '法人姓名',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'unified_code',
    label: '统一社会信用代码',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'address',
    label: '牧场地址',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'province',
    label: '省',
    width: 200,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return Province(cellValue)
    },
    search: {
      label: '110100',
      component: 'Select',
      componentProps: {
        options: city.area,
        onChange: provinceChange
      },
      show: true
    }
  },
  {
    field: 'city',
    label: '市',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return City(_, cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: cityData
      },
      show: true
    }
  },
  {
    field: 'owner_name',
    label: '牧场主姓名',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'phone',
    label: '联系电话',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'postal_code',
    label: '邮政编码',
    width: 150,
    table: {
      show: false
    }
  },
  {
    field: 'jurisdiction',
    label: '所属辖区',
    width: 150
  },
  {
    field: 'park_name',
    label: '关联园区',
    width: 150
  },
  {
    field: 'unified_code',
    label: '统一社会信用代码',
    width: 150
  },
  {
    field: 'business_license',
    label: '营业执照',
    width: 150,
    detail: {
      span: 2
    }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    width: 80,
    form: {
      show: false
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 170,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'action',
    width: 250,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'enclosure':
      push({
        path: '/Assets/xenclosure/enclosureList',
        query: {
          org_id: row.org_id,
          org_name: row.org_name
        }
      })
      break
    case 'assets':
      dialogTitle.value = row.org_name + '-资产列表'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'park':
      dialogTitle.value = row.org_name + '-关联园区'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    default:
      console.log('未知类型')
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()
const parkRef = ref<ComponentRef<typeof Park>>()
const loading = ref(false)

const save = async () => {
  const edit = unref(editRef)
  const park = unref(parkRef)
  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as any
          let res = await zcPastureEditApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'park':
      await park?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await park?.getFormData()) as any
          loading.value = false
          data.org_id = tableObject.currentRow.org_id

          let res = await zcPastureEditParkApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}
</script>

<template>
  <ContentWrap>
    <Search
      ref="searchRef"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />
    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    >
      <template #action="{ row }">
        <ElButton circle :icon="iconEdit" @click="action('edit', row)" title="编辑" />
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />
        <ElButton circle :icon="iconEnclosure" @click="action('enclosure', row)" title="栏位" />
        <ElButton circle :icon="iconAssets" @click="action('assets', row)" title="打标资产" />
        <ElButton circle :icon="iconPark" @click="action('park', row)" title="关联园区" />
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit v-if="actionType == 'edit'" ref="editRef" :id="tableObject.currentRow.org_id" />

    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <Assets
      v-if="actionType == 'assets'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <Park v-if="actionType == 'park'" ref="parkRef" :current-row="tableObject.currentRow" />

    <template #footer>
      <ElButton
        v-if="actionType == 'edit' || actionType == 'assets' || actionType == 'park'"
        type="primary"
        :loading="loading"
        @click="save()"
      >
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
